package fi.jamk.ourcookingapp.backend.architecture.manager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import fi.jamk.ourcookingapp.backend.architecture.interfaces.ICommentManager;
import fi.jamk.ourcookingapp.backend.architecture.json.WebService;
import fi.jamk.ourcookingapp.backend.model.Comment;
import fi.jamk.ourcookingapp.backend.model.Receipt;
import fi.jamk.ourcookingapp.backend.model.User;

public class CommentManager implements ICommentManager {

	private static final String CONTROLLER = "comment";
	
	@SuppressLint("SimpleDateFormat")
	private SimpleDateFormat sdfToDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	@Override
	public boolean createComment(Comment comment) throws InterruptedException, ExecutionException, JSONException {
		String getData = "user_id=>" + comment.getUser().getID() + "&receipt_id=>" + comment.getRecipt().getID() + "&text=>" + comment.getText() + "&parent_comment_id=>" + comment.getParentComment();
        AsyncTask<String, Void, JSONObject> result = new WebService().execute(getData, CONTROLLER, "create");
		boolean obj = result.get().getBoolean("comment");
		if(!obj){
			// TODO
		}
		return obj;
	}

	@Override
	public List<Comment> commentsByReceipt(Receipt receipt) throws InterruptedException, ExecutionException, JSONException {
		List<Comment> result = new ArrayList<Comment>();
		String getData = "receipt_id=>" + receipt.getID();
		AsyncTask<String, Void, JSONObject> JSONresult = new WebService().execute(getData, CONTROLLER, "commentsByReceipt");
		JSONObject obj = JSONresult.get();
		try {
			JSONArray comments = obj.getJSONArray("comments");
			for (int i=0;i < comments.length();i++) {
				JSONObject JSONcom = comments.getJSONObject(i);
				Comment com = new Comment();
				try {
					com.setDate(sdfToDate.parse(JSONcom.getString("date")));
				} catch (ParseException e) {
				}
				com.setID(JSONcom.getInt("id"));
				com.setParentComment(JSONcom.getInt("parent_comment_id"));
				com.setReciept(receipt);
				com.setText(JSONcom.getString("text"));
				com.setUser(new User(JSONcom.getString("loginName"), JSONcom.getInt("user_id")));
				result.add(com);
			}
		} catch (Exception e) {

		}
		return result;
	}

}
